package com.jackrain.nea.oms.mq;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.impl.util.MsgConvertUtil;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.oms.services.DatavServies;
import com.jackrain.nea.oms.services.SendMqServies;
import com.jackrain.nea.util.ApplicationContextHandle;
import lombok.extern.slf4j.Slf4j;

import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;

import static com.aliyun.openservices.ons.api.Action.CommitMessage;

/**
 * @Discription: 大屏数据监听
 * Created with IntelliJ IDEA.
 * @Author xyc
 */
@Slf4j
public class DatavListener implements MessageListener {

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        PropertiesConf propertiesConf = ApplicationContextHandle.getBean(PropertiesConf.class);
        SendMqServies sendMq = ApplicationContextHandle.getBean(SendMqServies.class);
        try {
            if (propertiesConf.getProperty("ons.datavTopic").equals(message.getTopic())) {
                mqConsume(message, consumeContext);
            } else {
                log.error("不是datav监听的任务");
            }
            return CommitMessage;
        } catch (Exception e) {
            e.printStackTrace();
            return CommitMessage;
        }
    }

    /**
     * datav
     *
     * @param message
     * @param consumeContext
     * @throws Exception
     */
    private void mqConsume(Message message, ConsumeContext consumeContext) throws Exception {
        String msgStr = MsgConvertUtil.objectDeserialize(message.getBody()).toString();
        JSONObject jsonObject = JSONObject.parseObject(msgStr);

        DatavServies datavServies = ApplicationContextHandle.getBean(DatavServies.class);
        if (jsonObject == null) {
            throw new NDSException("datav信息为空！！！");
        }
        log.debug("datav=" + jsonObject.toJSONString());
        datavServies.synchronizeData(jsonObject, message.getKey(), message.getTopic(), message.getTag());
    }
}
